//
//  VideoCropController.swift
//  teacher
//
//  Created by raniys on 2018/10/22.
//

import UIKit
import AVKit
import AVFoundation
import CoreMedia


class VideoCropController: UIViewController {

    // MARK: - Properties
    
    
    var videoUrl: URL!
    var avAsset: AVAsset?
    var imageTime: CMTime?

    var completionHandler: ((UIImage?, String?) -> Void)?
    
    var themeColor: UIColor = UIColor.blue
    var backButtonImage: UIImage? = UIImage(named: "navbar_back_white")
    var doneButtonTitleColor: UIColor = UIColor.white
    var doneButtonBackgroundImage: UIImage?
    
    
    @IBOutlet weak var videoCropView: VideoCropView!
    @IBOutlet weak var selectThumbView: ThumbSelectorView!
    
    
    // MARK: - Life Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configureViews()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        loadAsset()
    }
    
    func configureViews() {
        
        let leftButton = UIButton(type: .custom)
        leftButton.setImage(backButtonImage, for: .normal)
        leftButton.addTarget(self, action: #selector(leftButtonTapped(_:)), for: .touchUpInside)
        leftButton.sizeToFit()
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
        
        let rightButton = UIButton(type: .custom)
        rightButton.setTitleColor(doneButtonTitleColor, for: .normal)
        rightButton.setTitle("完成", for: UIControl.State())
        rightButton.setBackgroundImage(doneButtonBackgroundImage, for: .normal)
        rightButton.setBackgroundImage(doneButtonBackgroundImage, for: .selected)
        rightButton.setBackgroundImage(doneButtonBackgroundImage, for: .highlighted)
        rightButton.titleLabel?.font = UIFont.size(14, type: .medium)
        rightButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 18, bottom: 4, right: 18)
        rightButton.clipsToBounds = true
        rightButton.addTarget(self, action: #selector(self.rightButtonTapped(_:)), for: .touchUpInside)
        rightButton.sizeToFit()
        rightButton.layer.cornerRadius = rightButton.height / 2
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        title = "选择封面"

        selectThumbView.thumbBorderColor = themeColor
        selectThumbView.thumbnailImageWidth = 32
        selectThumbView.reloadViews()
    }
    
    func loadAsset() {
        avAsset = AVURLAsset(url: videoUrl)
        videoCropView.asset = avAsset
        selectThumbView.asset = avAsset
        selectThumbView.delegate = self
    }
    
    @objc func leftButtonTapped(_ sender: UIButton? = nil) {
        
        let alert = UIAlertController(title: "返回上一步会丢失当前数据，确定返回吗？", message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (action) in
            self.completionHandler?(nil, nil)
            
            if self.navigationController?.viewControllers.count ?? 0 > 1 {
                self.navigationController?.popViewController(animated: false)
            } else {
                self.dismiss(animated: false, completion: nil)
            }
        }))
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    @objc func rightButtonTapped(_ sender: UIButton?) {
        let time = imageTime ?? CMTime(seconds: 0.1, preferredTimescale: 1000)
        
        var coverImage: UIImage?
        var fileName: String?
        
        if let avAsset = avAsset {
            let generator = AVAssetImageGenerator(asset: avAsset)
            generator.requestedTimeToleranceBefore = CMTime.zero
            generator.requestedTimeToleranceAfter = CMTime.zero
            generator.appliesPreferredTrackTransform = true
            var actualTime = CMTime.zero
            let image = try? generator.copyCGImage(at: time, actualTime: &actualTime)
            if let image = image {
                coverImage = UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .up)
            }
        }
        
        completionHandler?(coverImage, "")
        print("rightButtonTapped")
        
        if navigationController?.viewControllers.count ?? 0 > 1 {
            navigationController?.popViewController(animated: false)
        } else {
            dismiss(animated: false, completion: nil)
        }
    }
}


extension VideoCropController: ThumbSelectorViewDelegate {
    
    func didChangeThumbPosition(_ imageTime: CMTime) {
        self.imageTime = imageTime
        videoCropView.player?.seek(to: imageTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
    }
}

extension UIImage {
    
    func crop(in frame: CGRect) -> UIImage? {
        
        if let croppedImage = self.cgImage?.cropping(to: frame) {
            return UIImage(cgImage: croppedImage, scale: scale, orientation: imageOrientation)
        }
        return nil
    }
}
